package prj.common.bean;

import javax.faces.component.UIInput;
import javax.faces.event.AjaxBehaviorEvent;

import org.springframework.beans.factory.annotation.Autowired;

import prj.common.exception.EmptyCaptchaException;
import prj.common.exception.InvalidCaptchaException;
import prj.common.service.CaptchaService;

public abstract class CaptchaSupportedBean extends FormHandlerBean {
	private static final long serialVersionUID = 1L;
    
	private String captchaValue;
	private String captchaError;
	private CaptchaService captchaService;
	protected String captchaField;
	
	public CaptchaSupportedBean() {
		super();
		setCaptchaField();
	}
	
	public String getCaptchaValue() {
		return captchaValue;
	}
	public void setCaptchaValue(String captchaValue) {
		this.captchaValue = captchaValue;
	}
	public String getCaptchaError() {
		return captchaError;
	}
	public void setCaptchaError(String captchaError) {
		this.captchaError = captchaError;
	}
	public String getCaptchaField() {
		return captchaField;
	}
	public abstract void setCaptchaField();
	@Autowired
	public void setCaptchaService(CaptchaService captchaService) {
		this.captchaService = captchaService;
	}
	public void validate(AjaxBehaviorEvent e) {
		if (e.getComponent() instanceof UIInput) {
			UIInput input = (UIInput)e.getComponent();
			String value = (String)input.getValue();
			if (input.getId().equals(captchaField)) validateCaptcha(value);
		}
	}
	public void validateCaptcha(String captcha) {
		captchaError = null;
		
		try {
			captchaService.validateCaptcha(captcha,captchaField);
		} catch (EmptyCaptchaException e) {
			captchaError = handleFormMessage("contactme_captcha_error_required");
		} catch (InvalidCaptchaException e) {
			captchaError = handleFormMessage("contactme_captcha_error_failed");
		}
	}
}
